/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core.event;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.core.MetadataCoreManager;
import com.inspur.edp.lcm.metadata.core.MetadataProjectCoreService;
import com.inspur.edp.lcm.metadata.spi.event.DirEventArgs;
import com.inspur.edp.lcm.metadata.spi.event.DirEventListener;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class DirEventListenerImpl implements DirEventListener {
	@Override
	public void fireDirDeletingEvent(DirEventArgs args) {
		// 获取目录下的元数据，将id和filename存入字典
		List<GspMetadata> metadataListInDir = MetadataCoreManager.getCurrent().getMetadataList(args.getPath());
		// 目录下无元数据，直接删除。
		if (CollectionUtils.isEmpty(metadataListInDir)) {
			return;
		}

		Map<String, String> filesInDir = new HashMap<>();
		metadataListInDir.forEach(metadata ->
		{
			filesInDir.put(metadata.getHeader().getId(), metadata.getHeader().getFileName());
		});
		// 获取工程下的元数据
		MetadataProject project = MetadataProjectCoreService.getCurrent().getMetadataProjInfo(args.getPath());
		// 非工程文件夹，直接删除
		if (project == null) {
		    return;
        }
		List<GspMetadata> metadataListInProject = MetadataCoreManager.getCurrent().getMetadataList(project.getProjectPath());

		// 排除目录下的元数据
		List<GspMetadata> metadataListExclude = metadataListInProject.stream().filter(item -> !filesInDir.containsKey(item.getHeader().getId())).collect(Collectors.toList());

		metadataListExclude.forEach(metadata ->
		{
			metadata.getRefs().forEach(item ->
			{
				if (filesInDir.containsKey(item.getDependentMetadata().getId())) {
					String message = "元数据" + filesInDir.get(item.getDependentMetadata().getId()) + "被文件夹外的元数据" + metadata.getHeader().getFileName() + "依赖，请清除其中依赖后重试。";
					throw new RuntimeException(message);
				}
			});
		});
	}

	@Override
	public void fireDirDeletedEvent(DirEventArgs args) {
        MetadataCoreManager.getCurrent().removeMetadataListCache(args.getPath());
	}
}
